package com.ruoyi.system.outto.game.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.SSGAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SSGApiImpl implements SSGAPI {

    private SalePartner salePartner;
    @Autowired
    private CommonApi commonApi;
    @Resource
    private InfoImgMapper infoImgMapper;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,"open.api.save",salePartner);
        Map<String, Object> result = new HashMap<>();

        String sign = getSign(params);
        params.put("sign", sign);
        log.info("SSG添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtil.post(salePartner.getTwoOther(),params,10000);
        log.info("SSG添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    public Map<String,Object> params(AccountInfo accountInfo,String type,SalePartner sa){


        Map<String,Object> content = new HashMap<>();
        content.put("order_no",accountInfo.getId());
        content.put("number",accountInfo.getId());
        content.put("app_id",this.salePartner.getOther());
        content.put("account_details",accountInfo.getDes());
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(),  sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(), sa);
        content.put("price",bigDecimal);

        if (Objects.equals(accountInfo.getLevel(), LCConstant.rezhengMial)){
            content.put("realname_type","1");
        }else {
            content.put("realname_type","2");
        }

        content.put("important_role","");
        content.put("email_type","1");
        content.put("role_weapons","");
        if (Objects.equals(accountInfo.getLevel(), LCConstant.rezhengMial)){
            content.put("is_email_realname","1");
        }else {
            content.put("is_email_realname","0");
        }
        content.put("is_send_mail","0");
        content.put("is_tap","0");
        content.put("is_psn","0");
        content.put("realPrice",bigDecimal);
        content.put("remake",accountInfo.getDes());

        if (Objects.isNull(accountInfo.getTitleImg())){
            content.put("title_img",this.salePartner.getThreeOther());
        }else {
            content.put("title_img",accountInfo.getTitleImg());
        }



        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            imgs =  this.salePartner.getTwoOther();
        }
        content.put("img_list",imgs);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_id", this.salePartner.getOther());
        paramMap.put("method", type);
        paramMap.put("version", "1.0");
        paramMap.put("api_request_id", UUIDGenerator.generate12());
        paramMap.put("charset", "utf-8");


        Map<String,Object> game_accountsMap = new HashMap<>();


        if ("open.api.edit".equals(type)){
            game_accountsMap.put("game_account",content);
        }else {
            List<Map<String,Object>> game_accounts = new ArrayList<>();
            game_accounts.add(content);
            game_accountsMap.put("game_accounts",game_accounts);
        }

        paramMap.put("content", JSONObject.toJSONString(game_accountsMap));
        paramMap.put("sign_type", "RSA2");

        return paramMap;


    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(accountInfo,"open.api.edit",salePartner);
        Map<String, Object> result = new HashMap<>();
        String sign = getSign(params);
        params.put("sign", sign);
        log.info("SSG编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtil.post(salePartner.getTwoOther(),params,10000);
        log.info("SSG编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(Long id, Long userId, SalePartner salePartner) {

        this.salePartner = salePartner;


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_id", this.salePartner.getOther());
        paramMap.put("method", "open.api.undercarriage");
        paramMap.put("version", "1.0");
        paramMap.put("api_request_id", UUIDGenerator.generate12());
        paramMap.put("charset", "utf-8");
        paramMap.put("sign_type", "RSA2");

        paramMap.put("content", id + "");
        String sign = getSign(paramMap);
        paramMap.put("sign", sign);


        Map<String, Object> result = new HashMap<>();

        log.info("SSG删除接口请求参数={}", JSONObject.toJSONString(paramMap));
        String response = HttpUtil.post(salePartner.getTwoOther(),paramMap,10000);
        log.info("SSG删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(paramMap));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);

    }

    private static final String PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFx5NMt9TfEcF65BNEy3LWXzQi0TFQDMHVbNi35NOralc7qMRpX29A6F6pz5aU5458uiMQf3s1NFf9sRS3X/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BgCTPmYHgW/+/DazV2zGAv5S6r3CbMJU6RPdUi1qOqPddN9/zBfwKBgA+022DTTEldZ/vtQW3cXtuVhOfuPPUNmT85EYMEN7/JvbLUnOho+hHrDfcwur0pOiOBn9P07EXYm2f2omdkcPAKGn9v2nHwq2XszB8BWrYyKMMBtiitwU5oLsu/1qhXETNGCaGkRifTTWkuJtnPkKKRk4+BE2Oj8paXeeoZMjBNAoGBANKDcHBNLt95HwMU8kmcXNVd7oF50B8gCcPNJYMxgYkVQxbo4XUWo+wLsJ58gj0c0RStAqQhbdJKI3CftpNCR4CvtJkpPLCd7M7Et7D3vcpr18y2hzd8Zjb04s4GAfMevE3fuXVUzLaFMhovC9ZB6j1bw5e0Q4GK76Yo9tN9hhk2";


    /**
     * 加签
     *
     * @param paramMap
     * @return
     */
    private String getSign(Map<String, Object> paramMap) {
        //map类型转换
        Map<String, String> map = new HashMap<>(paramMap.size());
        for (String s : paramMap.keySet()) {
            map.put(s, paramMap.get(s).toString());
        }

        try {
            TreeMap<String, String> signMap = new TreeMap<>();
            signMap.putAll(map);

            String charset = signMap.get("charset");
            String signType = signMap.get("sign_type");

            //待签名串
            signMap.remove("sign_type");
            signMap.remove("sign");
            String content = AlipaySignature.getSignContent(signMap);
            //签名
            return AlipaySignature.rsaSign(content, PRIVATE_KEY, charset, signType);
        } catch (Exception e) {
            throw new GlobalException("加签异常");
        }

    }
}
